var URL = "http://162.251.20.37:10010"; 

var md5 = require("md5");
var HTTP = cc.Class({
    extends: cc.Component,
    statics:{
        master_url:URL,
        url:URL,
        hotUrl:"",
        version:"1.0.0",
        reConnectCount:2,//重连次数
        /*
        功能：发送消息请求
        参数说明
        path：请求的协议地址
        data: 请求参数
        handler: 绑定回调
        sendType: 发送类型，默认POST
        outTime: 超时时间
        extraUrl：自定义需要连接的地址，默认URL地址
        */
        sendRequest : function(path,data,handler,sendType,outTime,extraUrl){
            //cc.log("http sendRequest");
            var xhr = cc.loader.getXMLHttpRequest();
            if(outTime == null){
                xhr.timeout = 5000;
            }
            else
            {
                xhr.timeout = outTime;
            }
            if(sendType == null){
                sendType = "POST"
            }
            if(extraUrl == null){
                extraUrl = HTTP.master_url;
            }

            //结构体------------------------------------------------
            var dataObj = new Object();
            dataObj = JSON.parse(JSON.stringify(data));
            var newTime = new Date().getTime();
            var timeUtc = newTime.toString();
           
            dataObj["TimeStamp"] = timeUtc;
            dataObj["Secret"] = "B30B505C43C22093FE3D056BCA2E4AED"; 
            var dataStr = "?";
            for(var k in dataObj){
                if(dataStr != "?"){
                    dataStr += "&";
                }
                dataStr += k + "=" + dataObj[k];
                if(dataStr === "?")
                    dataStr = "";
            }
            
            var dataMd5 = md5.hex_md5(dataStr);
            var dataTemp = new Object();
            dataTemp = JSON.parse(JSON.stringify(data));
            dataTemp["UnixTime"] = timeUtc;
            dataTemp["Digest"] = dataMd5;
            //------------------------------------------------------
            
            if(sendType == "POST" )
            {
                var str = "";
                for(var k in dataTemp){
                    if(str != ""){
                        str += "&";
                    }
                    str += k + "=" + dataTemp[k];
                }
                var requestURL = extraUrl + path ; 
                xhr.open(sendType,requestURL, true);
                //cc.log("http POST str:" + str);
                //cc.log("http POST RequestURL:" + requestURL);
            }
            else if(sendType == "GET")
            {
                var str = "?";
                for(var k in dataTemp){
                    if(str != "?"){
                        str += "&";
                    }
                    str += k + "=" + dataTemp[k];
                }
                if(str === "?")
                    str = "";
                var requestURL = extraUrl + path + str; 
                xhr.open(sendType,requestURL, true);
                //cc.log("http GET RequestURL:" + requestURL);
            }
            else if(sendType == "PUT")
            {
                var str = "";
                for(var k in dataTemp){
                    if(str != ""){
                        str += "&";
                    }
                    str += k + "=" + dataTemp[k];
                }
                var requestURL = extraUrl + path ; 
                xhr.open(sendType,requestURL, true);
          
                //cc.log("http PUT str:" + str);
                cc.log("http PUT RequestURL:" + requestURL);
            }

            xhr.onreadystatechange = function() {
                if((xhr.readyState === 4) && ((xhr.status >= 200 && xhr.status < 300) || (xhr.status === 0))){
                    //console.log("http res("+ xhr.responseText.length + "):" + xhr.responseText);
                    try {
                        var ret = JSON.parse(xhr.responseText);
                        //cc.log("http responseText:"+ xhr.responseText);
                        var obj = eval('('+ret+')');
                        //cc.log("http ret:"+ ret);

                        if(handler !== null){
                            handler(obj);
                        }  
                    } catch (e) {
                        cc.error("http erro:" + e);
                        xhr.abort();
                        xhr = null;
                        var data = {
                            Code :-1,
                            Msg: "连接失败",
                        };
                        handler(data);
                    }finally{
                    }
                }            
            };

            try {
                xhr.send(str);
            } catch (error) {
                cc.log("http erro:"+ error);
                xhr.abort();
                xhr = null;
                var data = {
                    Code :-1,
                    Msg: "发送请求失败",
                };
                handler(data);
                return null;
            }
            return xhr;
        },

        /*
        功能：发送消息请求扩展，自动检测重连 reconnectcount重连次数
        参数说明
        path：请求的协议地址
        data: 请求参数
        handler: 绑定回调
        sendType: 发送类型，默认POST
        outTime: 超时时间
        extraUrl：自定义需要连接的地址，默认URL地址
        */
        sendRequestRet : function(path,data,handler,sendType,outTime,extraUrl){
            //cc.log("http sendRequestRet");
            var self = this;
            var xhr = null;
            var pathTemp = path;
            var dataTemp = data;
            var sendTypeTemp = sendType;
            var outTimeTemp = (outTime==null || outTime == undefined)?null:outTime;
            var handlerTemp = handler;

            var count = 0;
            var fnRequest = function(){
                xhr = self.sendRequest(pathTemp,dataTemp,function(ret){
                    if(ret.Code == -1)
                    {
                        count++;
                        //cc.log("http reconnect"+count);
                        if(count >= self.reConnectCount)
                        {
                            handlerTemp(ret);
                        }
                        else
                            fnRequest();
                    }
                    else
                    {
                        handlerTemp(ret);
                    }
                },sendTypeTemp,outTimeTemp);
            }
            fnRequest();
        },

        /*
        功能：同步发送消息请求 暂未使用
        */
        sendSynchroRequest : function(path,data,sendType){
            //cc.log("http sendSynchroRequest");
            var xhr = cc.loader.getXMLHttpRequest();
            if(sendType == null){
                sendType = "POST"
            }

            if(sendType == "POST" )
            {
                var str = "";
                for(var k in data){
                    if(str != ""){
                        str += "&";
                    }
                    str += k + "=" + data[k];
                }
                var requestURL = HTTP.master_url + path ;
                xhr.open(sendType,requestURL, false);
          
                //cc.log("http POST str:" + str);
                xhr.send(str);
                //cc.log("http POST RequestURL:" + requestURL);
            }
            else if(sendType == "GET")
            {
                var str = "?";
                for(var k in data){
                    if(str != "?"){
                        str += "&";
                    }
                    str += k + "=" + data[k];
                }
                if(str === "?")
                    str = "";
                var requestURL = HTTP.master_url + path + str; 
                xhr.open(sendType,requestURL, false);
                xhr.send();
                //cc.log("http GET RequestURL:" + requestURL);
            }
            else if(sendType == "PUT")
            {
               var str = "";
                for(var k in data){
                    if(str != ""){
                        str += "&";
                    }
                    str += k + "=" + data[k];
                }
                var requestURL = HTTP.master_url + path ; 
                xhr.open(sendType,requestURL, false);
                //cc.log("http PUT str:" + str);
                xhr.send(str);
                //cc.log("http PUT RequestURL:" + requestURL);
            }
            var result = xhr.status;
            //OK
            if((xhr.readyState === 4) && ((xhr.status >= 200 && xhr.status < 300) || (xhr.status === 0))){
                cc.log("http res("+ xhr.responseText.length + "):" + xhr.responseText);
                    try {
                        var ret = JSON.parse(xhr.responseText);
                        var obj = eval('('+ret+')');
                        xhr = null;
                        return obj;
                    } catch (e) {
                    }finally{

                    }
            }
            xhr = null;
            return null;
        }
       
    },
});




